package com.syh.niceweibo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.syh.niceweibo.common.AsyncImageLoader;
import com.syh.niceweibo.common.AsyncImageLoader.ImageCallback;
import com.syh.niceweibo.common.Constants;
import com.syh.niceweibo.common.Utils;
import com.syh.niceweibo.common.WeiboImpl;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;

public class MainActivity extends Activity implements OnClickListener,
		OnItemClickListener {
	// FINAL VAR
	public final static String TAG = "MainActivity";
	private final static int[][] TypeArray = new int[][] {
			{ R.drawable.meinv, R.string.meinv, 3 },
			{ R.drawable.mingche, R.string.mingche, 8 },
			{ R.drawable.xingzuo, R.string.xingzuo, 5 },
			{ R.drawable.meishi, R.string.meishi, 9 },
			{ R.drawable.shipin, R.string.shipin, 4 },
			{ R.drawable.gaoxiao, R.string.gaoxiao, 2 },
			{ R.drawable.meng, R.string.meng, 6 },
			{ R.drawable.yule, R.string.yule, 1 } };
	// ANDROID VAR
	private View mivSettings;
	private ImageView mivIcon;
	private TextView mtvName;
	private GridView mgvType;
	private TypeAdapter mAdapter;

	// JAVA VAR
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_main);
		initView();
		initListener();
		initData();
	}

	private void initView() {
		mivSettings = findViewById(R.id.ivSettings);
		mivIcon = (ImageView) findViewById(R.id.ivIcon);
		mtvName = (TextView) findViewById(R.id.tvName);
		mgvType = (GridView) findViewById(R.id.gvType);
	}

	private void initListener() {
		mivSettings.setOnClickListener(this);
		mgvType.setOnItemClickListener(this);
	}

	private void initData() {

		if (Utils.needLogin(MainActivity.this)) {
			startActivity(new Intent(MainActivity.this, LoginActivity.class));
			finish();
		} else {
			String icon = Utils.getUserIcon(getApplicationContext());
			String name = Utils.getUserName(getApplicationContext());
			if (TextUtils.isEmpty(icon) || TextUtils.isEmpty(name)) {
				String uid = Utils.getUID(getApplicationContext());
				loadUserInfo(uid);
			} else {
				updateUserUI(icon, name);
			}

			mgvType.setVisibility(View.VISIBLE);
			mAdapter = new TypeAdapter(MainActivity.this, TypeArray);
			mgvType.setAdapter(mAdapter);

		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ivSettings: {
			startActivity(new Intent(this, SettingsActivity.class));
			break;
		}
		}
	}

	private void updateUserUI(String icon_url, String name) {
		mivIcon.setVisibility(View.VISIBLE);
		mtvName.setVisibility(View.VISIBLE);
		Bitmap bitmap = AsyncImageLoader.getInstance().loadBitmap(icon_url,
				new ImageCallback() {

					@Override
					public void imageLoaded(Bitmap imageBitmap, Object tag) {
						((ImageView) findViewById((Integer) tag))
								.setImageBitmap(imageBitmap);
					}
				}, R.id.ivIcon,0);
		if (bitmap != null) {
			mivIcon.setImageBitmap(bitmap);
		} else {
			mivIcon.setTag(mivIcon);
		}
		mtvName.setText(name);

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void loadUserInfo(String uid) {
		new AsyncTask() {

			@Override
			protected Object doInBackground(Object... params) {
				String uid = (String) params[0];
				try {
					String result = Weibo.getInstance().getUser(
							getApplicationContext(),
							Utils.getAccessToken(getApplicationContext()), uid);
					String[] user = WeiboImpl.getUserInfo(result);
					return user;
				} catch (WeiboException e) {
					e.printStackTrace();
				}

				return null;
			}

			protected void onPostExecute(Object result) {
				if (result != null) {
					String[] user = (String[]) result;
					String name = user[0];
					String icon = user[1];
					Utils.saveUserInfo(getApplicationContext(), name, icon);
					updateUserUI(icon, name);
				} else {
					Toast.makeText(getApplicationContext(),
							R.string.get_user_faild, 0).show();
				}
			};

		}.execute(uid);
	}

	private class TypeAdapter extends BaseAdapter {

		private int[][] mDataArray;
		private LayoutInflater inflater;

		public TypeAdapter(Context context, int[][] dataArray) {
			mDataArray = dataArray;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mDataArray != null ? (mDataArray[0].length == 3 ? mDataArray.length
					: 0)
					: 0;
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		public int getTypeId(int position) {
			return mDataArray[position][2];
		}

		public int getTypeName(int position) {
			return mDataArray[position][1];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.type_item, null);
				holder = new ViewHolder();
				holder.ivTypeIcon = (ImageView) convertView
						.findViewById(R.id.ivTypeIcon);
				holder.tvTypeName = (TextView) convertView
						.findViewById(R.id.tvTypeName);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.ivTypeIcon.setImageResource(mDataArray[position][0]);
			holder.tvTypeName.setText(mDataArray[position][1]);
			return convertView;
		}
	}

	private class ViewHolder {
		ImageView ivTypeIcon;
		TextView tvTypeName;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		int type = mAdapter.getTypeId(arg2);
		int name = mAdapter.getTypeName(arg2);
		Intent intent = new Intent(MainActivity.this, WeiboActivity.class);
		intent.putExtra(Constants.EXTRA_TYPE_ID, type);
		intent.putExtra(Constants.EXTRA_TYPE_NAME, name);
		startActivity(intent);

	}
}
